// ThinWorkerThread.cpp: implementation of the CThinWorkerThread class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ThinWorkerThread.h"
#include "process.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

//##ModelId=4396837702DF
CThinWorkerThread::CThinWorkerThread(LPCTSTR lpThreadName)
{
    m_hThread	= NULL;
    m_ThreadId	= 0;
	m_bSuspend	=FALSE;
	m_bRepeat	=TRUE;
	m_dwExitCode=-1;

	if (lpThreadName)
	{
		lstrcpyn(m_chThreadName,lpThreadName,99);
	}

}
//##ModelId=4396837702E1
CThinWorkerThread::~CThinWorkerThread()
{
	if(m_hThread!=NULL)
	{
		ExitThread();
		WaitForExit();
	}
}

//##ModelId=4396837702C8
BOOL CThinWorkerThread::StartThread()
{
	if(m_hThread)
		return TRUE;

	m_bRepeat	=TRUE;
	m_hThread=CreateThread(NULL,0,CThinWorkerThread::ThreadFunc,(LPVOID)this,0,&m_ThreadId);
	if(!m_hThread)
		return FALSE;
	return TRUE;
}
//##ModelId=4396837702C9
void CThinWorkerThread::WaitForExit(DWORD dwTimeOut)
{
	DWORD	dwResult;
	if(m_hThread==NULL)
		return;

// 	if(dwTimeOut<0)
// 		dwTimeOut=0;
	dwResult=WaitForSingleObject(m_hThread, dwTimeOut);
	switch(dwResult)
	{
	case WAIT_TIMEOUT:
		Terminate();
		break;
	case WAIT_OBJECT_0:
		break;
	default:
		Terminate();
		break;
	}

    CloseHandle(m_hThread);
	m_hThread=NULL;


}
//##ModelId=4396837702DC
DWORD WINAPI CThinWorkerThread::ThreadFunc(LPVOID param)
{
    // Use the param as the address of the object
    CThinWorkerThread* pwt = (CThinWorkerThread*)param;
    // Call the member function. Since we have a
    // proper object pointer, even virtual functions
    // will be called properly.
    pwt->GetExitCode() = pwt->ThreadMemberFunc();
	return pwt->m_dwExitCode;
}


//
// This above function ThreadObject::ThreadFunc()
// calls this function after the thread starts up.
//
//##ModelId=4396837702DA
DWORD CThinWorkerThread::ThreadMemberFunc()
{
    // Do something useful ...
//	TRACE("CThinWorkerThread::ThreadMemberFunc\n");
	return 0;
}
//##ModelId=4396837702CB
void	CThinWorkerThread::Terminate()
{
	if(m_hThread!=NULL)
		TerminateThread(m_hThread,0);
	CloseHandle(m_hThread);
	m_hThread=NULL;
}
//##ModelId=4396837702CC
BOOL	CThinWorkerThread::Resume()
{
	DWORD	dwResult=0;
	if(m_hThread!=NULL && m_bSuspend)
	{
		dwResult=ResumeThread(m_hThread);
		if(dwResult!=-1)
		{
			m_bSuspend = FALSE;
		}
	}
	
	return	!m_bSuspend;
}

BOOL CThinWorkerThread::Suspend()
{
	DWORD	dwResult=0;
	if(m_hThread!=NULL && !m_bSuspend)
	{
		dwResult=SuspendThread(m_hThread);
		if(dwResult!=-1)
		{
			m_bSuspend = TRUE;
		}
	}
	return	m_bSuspend;
}
